package com.seele.tigerwallet.ui.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.seele.base.utils.CrashUtils;
import com.seele.base.utils.FileIOUtils;
import com.seele.base.utils.FileUtils;
import com.seele.base.utils.LogUtils;
import com.seele.base.utils.SDCardUtils;
import com.seele.tigerwallet.BuildConfig;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.jpush.JPushService;
import com.seele.tigerwallet.model.UserInfo;
import com.seele.tigerwallet.ui.constants.Constant;
import com.seele.tigerwallet.ui.orm.DatabaseHelper;
import com.seele.tigerwallet.ui.utils.DataUtils;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.ui.utils.SystemUtils;
import com.seele.tigerwallet.utils.SeeleFileMap;
import com.seele.tigerwallet.utils.Utils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SeeleApplication extends Application {


    private static SeeleApplication instance;
    private List<Activity> mActivitys = Collections
            .synchronizedList(new LinkedList<Activity>());

    public static SeeleApplication getInstance() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);

    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        Intent intent = new Intent(this, JPushService.class);
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startService(intent);
        //初始化数据库
        DatabaseHelper.setApplication(getApplicationContext());
        DatabaseHelper.getInstance().getReadableDatabase();


        //初始化用户信息类
        UserInfo.get();
        //初始化sp文件
        SPUtils.setContext(getApplicationContext());
        DataUtils.setContext(getApplicationContext());
        SeeleFileMap.setContext(this.getApplicationContext());
        //初始化工具类
        com.seele.base.utils.Utils.init(getApplicationContext());

        //初始化Log工具类
        initLogUtils();

        //初始化CrashUtils

        if (SDCardUtils.isSDCardEnableByEnvironment()) {
            String path = SDCardUtils.getSDCardPathByEnvironment();

            File file = new File(path + Constant.File.FILE_NAMA);
            CrashUtils.init();
        }


        //初始化地址
        APIModule.getApi();
        //初始化http参数
        APIModule.setParameter(getParameter());

        //友盟设置

        //设置LOG开关，默认为false
        UMConfigure.setLogEnabled(true);
        UMConfigure.init(this, "5b1a40c98f4a9d08b1000130", "Tiger100", UMConfigure.DEVICE_TYPE_PHONE, "");
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);

//        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "");
//        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);

        registerActivityLifecycleCallbacks();

    }

    private void initLogUtils() {
        final LogUtils.Config config = LogUtils.getConfig()
                .setLogSwitch(BuildConfig.DEBUG)// 设置 log 总开关，包括输出到控制台和文件，默认开
                .setConsoleSwitch(BuildConfig.DEBUG)// 设置是否输出到控制台开关，默认开
                .setGlobalTag(null)// 设置 log 全局标签，默认为空
                // 当全局标签不为空时，我们输出的 log 全部为该 tag，
                // 为空时，如果传入的 tag 为空那就显示类名，否则显示 tag
                .setLogHeadSwitch(true)// 设置 log 头信息开关，默认为开
                .setLog2FileSwitch(false)// 打印 log 时是否存到文件的开关，默认关
                .setDir("")// 当自定义路径为空时，写入应用的/cache/log/目录中
                .setFilePrefix("")// 当文件前缀为空时，默认为"util"，即写入文件为"util-MM-dd.txt"
                .setBorderSwitch(true)// 输出日志是否带边框开关，默认开
                .setSingleTagSwitch(true)// 一条日志仅输出一条，默认开，为美化 AS 3.1 的 Logcat
                .setConsoleFilter(LogUtils.V)// log 的控制台过滤器，和 logcat 过滤器同理，默认 Verbose
                .setFileFilter(LogUtils.V)// log 文件过滤器，和 logcat 过滤器同理，默认 Verbose
                .setStackDeep(1)// log 栈深度，默认为 1
                .setStackOffset(0);// 设置栈偏移，比如二次封装的话就需要设置，默认为 0
        LogUtils.d(config.toString());
    }


    /**
     * http请求公共参数设置
     *
     * @return
     */

    public Map<String, String> getParameter() {

        Map<String, String> map = new ConcurrentHashMap<>();
        map.put("channel", "1");
        map.put("ver", SystemUtils.getLocalVersion(getApplicationContext()) + "");
        map.put("platform", "Android");
        map.put("zone", "CN");
        return map;

    }

    private void registerActivityLifecycleCallbacks() {
        this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                mActivitys.add(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                if (null == mActivitys && mActivitys.isEmpty()) {
                    return;
                }
                if (mActivitys.contains(activity)) {
                    mActivitys.remove(activity);
                }
            }
        });
    }

    /**
     * @return 作用说明 ：获取当前最顶部activity的实例
     */
    public Activity getTopActivity() {
        Activity mBaseActivity = null;
        synchronized (mActivitys) {
            final int size = mActivitys.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = mActivitys.get(size);
        }
        return mBaseActivity;

    }

    public void clearActivitys() {
        if (mActivitys != null) {
            mActivitys.clear();
        }
    }

}
